import React, { Component, PropTypes } from 'react';
import classNames from 'classnames';

import TreeItemFile from './tree-item-file.jsx';
import TreeItemDir from './tree-item-dir.jsx';

/**
 * 目录树型
 * @class {DirectoryTree}
 * @extends {React.Component}
 */
export default class DirectoryTree extends Component {
    static propTypes = {
        /**
         * 目录树
         * @type {number|string}
         */
        tree: PropTypes.object,

        /**
         * 已展开的节点
         * @type {number|string}
         */
        expanded: PropTypes.object,

        /**
         * 当前焦点文件
         * @type {TabItem}
         */
        activePath: PropTypes.string,

        /**
         * 处理目录展开/关闭
         * @type {Function}
         */
        handleToggleCollapse: PropTypes.func,

        /**
         * 处理打开文件
         * @type {Function}
         */
        handleOpenFile: PropTypes.func
    };

    /**
     * 渲染树型节点
     * @param  {object} node
     * @param  {string} prefix
     * @return {Component}
     */
    renderTreeNode(node, prefix = '') {
        const { expanded, tree, activePath, handleToggleCollapse, handleOpenFile } = this.props;
        const path = `${prefix}/${node.name}`;
        const label = (
            <span className="label">{node.name}</span>
        );

        // 目录节点
        if (node.type === 'dir') {
            return (
                <TreeItemDir key={path}
                    renderTag="li"
                    name={node.name}
                    path={path}
                    collapsed={!(path in expanded)}
                    handleToggleCollapse={handleToggleCollapse}>
                    {node.children.map(child =>
                        this.renderTreeNode(child, path))}
                </TreeItemDir>
            );
        }

        // 文件节点
        return (
            <TreeItemFile key={path}
                renderTag="li"
                active={activePath === path}
                name={node.name}
                path={path}
                handleOpenFile={handleOpenFile} />
        );
    }

    render() {
        const { tree } = this.props;

        return (
            <ul className="tree-view-children">
                {tree.children.map(node =>
                    this.renderTreeNode(node))}
            </ul>
        );
    }
}